package com.flute.icrawler.htmlparser.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;

import org.w3c.dom.Document;

import com.flute.icrawler.htmlparser.HtmlParserException;
import com.flute.icrawler.htmlparser.IHtmlParser;
import com.flute.icrawler.htmlparser.dom.HtmlParser;
import com.flute.icrawler.htmlparser.http.HttpRequest;

public class BasicHtmlParser implements IHtmlParser {

	public BasicHtmlParser() {
		document = null;
		url = null;
		request = null;
		parser = null;
		request = new HttpRequest();
	}

	public InputStream request(String url) throws HtmlParserException {
		this.url = url;
		return request.getHttpResponseStream(url);
	}

	public InputStream request(String url, HashMap params)
			throws HtmlParserException {
		this.url = url;
		return request.getHttpResponseStream(url, params);
	}

	public Document getDocument(String url, HashMap params, int htmlType)
			throws HtmlParserException {
		Document document1;
		parser = new HtmlParser(url);
		document = parser.parser(request.getHttpResponseStream(url, params),
				htmlType);
		document1 = document;
		try {
			shutdown();
			return document1;
		} catch (Exception e) {

			shutdown();
			return null;
		}
	}

	public Document getDocument(File file, int htmlType)
			throws HtmlParserException {
		Document document1;
		try {
			parser = new HtmlParser(url);
			document = parser.parser(new FileInputStream(file), htmlType);
			document1 = document;
		} catch (Exception e) {
			throw new HtmlParserException(e);
		}
		try {
			shutdown();
			return document1;
		} catch (Exception exception) {
			shutdown();
			return null;
		}
	}

	public Document getDocument(String url, int htmlType)
			throws HtmlParserException {
		Document document1;
		parser = new HtmlParser(url);
		document = parser.parser(request.getHttpResponseStream(url), htmlType);
		document1 = document;
		try {
			shutdown();
			return document1;
		} catch (Exception exception) {
			shutdown();
			return null;
		}
	}

	public Document getDocument(InputStream in) throws HtmlParserException {
		try {
			parser = new HtmlParser();
			document = parser.parser(in, 1);
			return document;
		} catch (Exception e) {
			e.printStackTrace();
			throw new HtmlParserException(e);
		}
	}

	public void shutdown() {
		request.shutdown();
	}

	protected Document document;
	protected String url;
	protected int htmlType;
	private HttpRequest request;
	private HtmlParser parser;
}
